package com.qst.crop.controller;


import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.service.FileUploaderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileUploadController {
    @Autowired
    private FileUploaderService fileUploadService;


    @PostMapping("/upload/order")
    public Result uploadFileOrder(@RequestParam("file") MultipartFile file) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            JwtUser principal = (JwtUser) authentication.getPrincipal();
            String username = principal.getUsername();
            fileUploadService.uploadFile("order",username,file);
            return new Result<>(true, StatusCode.OK,"上传成功",666);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(true, StatusCode.OK,e.getMessage());
        }
    }

    @PostMapping("/upload/avatar")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            JwtUser principal = (JwtUser) authentication.getPrincipal();
            String username = principal.getUsername();
            fileUploadService.uploadFile("avatar",username,file);
            return new Result<>(true, StatusCode.OK,"上传成功",file.getName());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(true, StatusCode.OK,e.getMessage());
        }
    }

    @PostMapping("/uploadInfo/info")
    public Result uploadFileInfo(@RequestParam("file") MultipartFile file) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            JwtUser principal = (JwtUser) authentication.getPrincipal();
            String username = principal.getUsername();
            fileUploadService.uploadFile("info",username,file);
            return new Result<>(true, StatusCode.OK,"上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(true, StatusCode.OK,e.getMessage());
        }
    }








}
